package com.baomidou.springwind.controller.supply;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.springwind.controller.BaseController;
import com.baomidou.springwind.entity.NetworkDelivery;
import com.baomidou.springwind.entity.OrderData;
import com.baomidou.springwind.entity.Project;
import com.baomidou.springwind.mapper.NetworkDeliveryDao;
import com.baomidou.springwind.service.OrderDataService;
import com.baomidou.springwind.service.ProjectService;
import com.baomidou.springwind.utils.ParamMap;
import com.baomidou.springwind.utils.ZvalueUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.springwind.mapper.OrderDataDao;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 物流供应链-库存持有成本
 * </p>
 *
 * @Author huangtao
 * @Date 2017-8-21
 */
@Controller
@RequestMapping("/network/supply")
public class OrderDataController extends BaseController {

    @Autowired
    private OrderDataService orderDataService;

    @Autowired
    private OrderDataDao orderDataDao;

    @Autowired
    private NetworkDeliveryDao networkDeliveryDao;

    @Autowired
    private ProjectService projectService;
    /**
     * 供应链数据导入
     */
    @RequestMapping("/order/list")
    @Permission("1001")
    public String inventoryList(Model model) {
        EntityWrapper<Project> wrapper = new EntityWrapper<Project>();
        wrapper.eq("operator_id",getCurrentUserId());
        wrapper.in("state", Arrays.asList("1", "2"));
        model.addAttribute("prjList", projectService.selectList(wrapper));
        return pjaxPath("/file/order_data_list", model);
    }

    /**
     * 库存持有成本数据--ajax获取数据
     */
    @ResponseBody
    @RequestMapping("/order/getData")
    @Permission("1001")
    public String getData(Page<OrderData> page) {
        page = new Page<OrderData>(page.getCurrent(), page.getSize());
        EntityWrapper<OrderData> wrapper = new EntityWrapper<OrderData>();
        String batchId=request.getParameter("batchId");
        if (batchId==null){
            batchId=getProjectId();
            if(batchId.length()==0){
                batchId="-1";
            }
        }
        wrapper.eq("batch_id",batchId);
        wrapper.eq("operator_id", getCurrentUserId());
        wrapper.orderBy("create_time", false);
        page = orderDataService.selectPage(page, wrapper);
        List<OrderData> orderDataList = page.getRecords();
        if (orderDataList.size() > 0) {
            Project project = projectService.selectById(orderDataList.get(0).getBatchId());
            for (OrderData orderData : orderDataList) {
                orderData.setBatchName(project == null ? "--" : project.getName());
            }
        }
        return jsonPage(page);
    }

    /**
     * 库存持有成本分析界面
     */
    @RequestMapping("/order")
    @Permission("1001")
    public String inventory(Model model) {
        EntityWrapper<OrderData> wrapper = new EntityWrapper<OrderData>();
        wrapper.eq("operator_id",getCurrentUserId());
        wrapper.eq("batch_id",getProjectId());
        wrapper.groupBy("branch_id");
        model.addAttribute("prjList", orderDataService.selectList(wrapper));
        return pjaxPath("/lpp/network/supply/order/main", model);
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/order/bar1")
    public String getbar1(Long batch, Model model) {
        String goodsPrice=request.getParameter("goodsPrice");
        String center=request.getParameter("center");
        if(center.length()==0){
            center=getCenter();
        }
        EntityWrapper<NetworkDelivery> wrapper1 = new EntityWrapper<NetworkDelivery>();
        wrapper1.eq("batch_id", getProjectId());
        List<NetworkDelivery> deliveryList = networkDeliveryDao.selectList(wrapper1);
        EntityWrapper<OrderData> wrapper2 = new EntityWrapper<OrderData>();
        wrapper2.eq("batch_id", getProjectId());
        List<OrderData> orderDataList = orderDataDao.selectList(wrapper2);
        Map<String, Object> pm1 =new HashMap<String,Object>();
        pm1.put("batchId",getProjectId());
        List<Map<String, Object>> inventoryCostList = orderDataDao.select1(pm1);
        List<Map<String, Object>> orderSuceess1=orderDataDao.selectOrderSuceess(pm1);
        List<Map<String, Object>> orderSuceess2=orderDataDao.selectDeliveryReliabilityCounts(pm1);
        JSONObject ret = bars(center,goodsPrice,deliveryList,orderDataList,inventoryCostList,orderSuceess1,orderSuceess2);
        if(ret.get("fail")!=null){
            return callbackFail(ret.get("fail").toString());
        }
        return callbackSuccess(ret);
    }
    public String getCenter(){
        List<Map<String, Object>> list = orderDataDao.selectCenter(getProjectId());
        if (list.size()>0){
            return list.get(0).get("branch_id").toString();
        }
        return null;
    }
    public JSONObject moneyLevel(String goodsPrice,List<OrderData> orderDataLists,List<Map<String, Object>> inventoryCostList2){
        JSONObject ret = new JSONObject();
        double price=Double.valueOf(goodsPrice);
        int delayedDays=0;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//创建日期转换对象HH:mm:ss为时分秒，年月日为yyyy-MM-dd
        List<Long> list=new ArrayList<Long>();
        Long advanceTimeSum=0L;
        List<OrderData> orderDataList = null;
        int demandSum=0;
        for (int i=0;i<orderDataLists.size();i++){
            demandSum=demandSum+orderDataLists.get(i).getOrderQuantity();
            try {
                Date carArrive= orderDataLists.get(i).getCarArrive();
                Date promiseArrival= orderDataLists.get(i).getPromiseArrival();
                Date preparationCar= orderDataLists.get(i).getPreparationCar();
                if (carArrive.getTime()<promiseArrival.getTime()) {
                    delayedDays++;
                }
                long diff=carArrive.getTime()-preparationCar.getTime();
                long days=diff/(1000*60*60*24);
                list.add(days);
                advanceTimeSum=advanceTimeSum+days;
            }catch (Exception e){
                String message="订单数据的时间没有上传,请加上时间后，重新上传订单数据";
                ret.put("fail",message);
                System.out.println("时间有NULL的");
                return ret;
            }
        }
        //服务水平
        DecimalFormat decimalFormat= new DecimalFormat("######0.00");
        double serviceLevel=((double)delayedDays)/((double) orderDataLists.size());
        String serviceLevelString=decimalFormat.format(serviceLevel);
        //计算提前期的标准差
        double advanceAvg=((double)advanceTimeSum)/((double) orderDataLists.size());
        double advanceStandard=0;
        for (int i=0;i<list.size();i++){
            advanceStandard=advanceStandard+(list.get(i)-advanceAvg)*(list.get(i)-advanceAvg);
        }
        double demadAvg=demandSum/inventoryCostList2.size();
        //计算的日需求量标准差
        double demadStandard=0;
        for (int i=0;i<inventoryCostList2.size();i++){
            demadStandard=demadStandard+(Integer.valueOf(inventoryCostList2.get(i).get("ordersum").toString())-demadAvg)*(Integer.valueOf(inventoryCostList2.get(i).get("ordersum").toString())-demadAvg);
        }
        double z=ZvalueUtil.getZ(serviceLevelString);
        double value= z*Math.sqrt(demadStandard/inventoryCostList2.size()*advanceAvg+advanceStandard/list.size()*demadAvg*demadAvg);

        //一级配送中心再订货点
        double orderPort=value+demadAvg*advanceAvg;
        //订货周期内的周转库存
        double turnoverInventory;
        double dateInterval=0;
        for (int i=1;i<=inventoryCostList2.size();i++){
            try{
                Date preparationCar1=df.parse(inventoryCostList2.get(i-1).get("preparationCar").toString());
                Date preparationCar2=df.parse(inventoryCostList2.get(i).get("preparationCar").toString());
                long diff=preparationCar2.getTime()-preparationCar1.getTime();
                long days=diff/(1000*60*60*24);
                dateInterval=dateInterval+days;
            }catch (Exception e){
            }
        }
        double dateIntervalAvg=dateInterval/inventoryCostList2.size();
        turnoverInventory=dateIntervalAvg*demadAvg;
        //订货周期内的最大库存
        double maxInventory=turnoverInventory+value;
        //订货周期内的平均库存
        double avgInventory=value+turnoverInventory/2;
        //订货周期内库存商品占用资金水平
        double moneyLevel=avgInventory*price;
        //一级配送中心1个月的平均库存
        double months=30;
        double monthAvgInventory=(months/dateIntervalAvg)*avgInventory;
        //到各二级配送中心的总订单量
        double toSecondaryCenter=demandSum;
        ret.put("safetyStock",1+(int)value);
        ret.put("orderPort",1+(int)orderPort);
        ret.put("turnoverInventory",1+(int)turnoverInventory);
        ret.put("maxInventory",1+(int)maxInventory);
        ret.put("avgInventory",1+(int)avgInventory);
        ret.put("moneyLevel",1+(int)moneyLevel);
        ret.put("monthAvgInventory",1+(int)monthAvgInventory);
        ret.put("toSecondaryCenter",1+(int)toSecondaryCenter);
        return ret;
    }
    public JSONObject bars(String center,String goodsPrice,List<NetworkDelivery> d1,List<OrderData> orderDataList,List<Map<String, Object>> inventoryCostList,List<Map<String, Object>> orderSuceess1,List<Map<String, Object>> orderSuceess2){
            List<Map<String, Object>> inventoryCostList2=new ArrayList<Map<String, Object>>();
            List<OrderData> orderDataList1=new ArrayList<OrderData>();
            long id=Long.valueOf(center);
            for (Map<String, Object> map:inventoryCostList){
                if (Long.valueOf(map.get("branchId").toString())==id){
                    inventoryCostList2.add(map);
                }
            }
            for (int j=0;j<orderDataList.size();j++){
                if(id==orderDataList.get(j).getBranchId()) {
                    orderDataList1.add(orderDataList.get(j));
                }
            }
            JSONObject ret=moneyLevel(goodsPrice,orderDataList1,inventoryCostList2);
            return ret;
    }



}
